<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>MCU Conference</title>
    <style type="text/css">
        body {
            margin: 0;
            padding: 0;
            background-color: #2E2D2E;
            overflow:hidden;
        }
    </style>
    <script type="text/javascript" src="SkyRTC-client.js"></script>
    <script type="text/javascript" src="jquery-1.10.2.js"></script>
    <script src="jquery-ui-1.10.1.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="camerainfos.js"></script>
    <script type="text/javascript" src="move.js"></script>
    <script type="text/javascript" src="splitscreen.js"></script>
    <script type="text/javascript">
        var  rtc;
        var mcu = VideoMCU();   //分屏MCU

        var currRoomNum;//获取参数roomNum
        var userID; //用户id
        var userName; //用户姓名
        var defaultShowVideo; //默认是否显示视频
        var currVideoId; //当前正在使用的摄像头id

        function init() {
            currRoomNum = request("roomNum");
            userID = request("userId");
            userName = request("userName");
            defaultShowVideo = request("defaultShowVideo") || "show";

            //初始化RTC相关的回调函数
            initRTC();
            //初始化MCU分屏功能
            mcu.init({
                "defaultImgPath": "defaultConf.bmp",    //无视频时的默认图片路径
                "videoContainerId": "screenContainer"   //视频容器div
            });

            var videoName = request("videoName");
            //去除字符串中的双引号
            videoName = videoName.replace(/\"/g,"");

            //获取摄像头列表，并在获取后进行初始化
            initAndGetCameraInfos(function(videoInfos){
                //如果url中未指定摄像头，则自己指定
                if(videoName == null || videoName.length==0){
                    //获取摄像头列表的第一个摄像头，作为默认摄像头
                    currVideoId = getFreeCamId();
                }else{  //如果已指定，则需要根据名称获取摄像头id
                    currVideoId = getCameraIdByName(videoName);
                }

                if(currVideoId==null || currVideoId.length==0){
                    console.log("MCU初始化失败，因未获取到有效的摄像头");
                    return;
                }

                if(currRoomNum!=null && currRoomNum.length>0){
                    join(currRoomNum);
                }
            });
        }

        function initRTC(){
            rtc = SkyRTC();

            //成功创建WebSocket连接
            rtc.on("socket_connected", function (socket) {
                var audio = request("audio");
                var speaker = request("speaker");
                audio = getParams(audio);
                speaker = getParams(speaker);
                console.info("音频状态是:" + audio + ", speaker:" + speaker);
                console.info("创建WebSocket的时候audio=" + audio);
                //创建本地视频流
                if (currVideoId == "" || currVideoId == undefined) {
                    console.log("摄像头未指定，使用默认摄像头来进行rtc.createStream");
                    currVideoId = null;
                }

                rtc.createStream({//设置分辨率是320*180//684,513//640*480
                    video: {
                        mandatory: {"maxWidth": "1920", "maxHeight": "1080"},
                        "optional": [{"sourceId": currVideoId}, {"frameRate": 60}, {"aspectRatio": 16 / 9}]
                    },
                    audio: audio
                });
            });

            //断开WebSocket连接
            rtc.on("socket_closed", function(socket){
                console.log("WebSocket连接已断开，开始重置RTC与MCU");
                //断开后重新初始化rtc，防止后面再次调用
                initRTC();
                //清理页面
                mcu.cleanUp();
                console.log("RTC与MCU重置完毕");
            });

            //创建本地视频流成功
            rtc.on("stream_created", function (stream) {
                var myVideoUrl = URL.createObjectURL(stream);
                var user1 = {"userId": userID, "userName":userName, "videoPosition": 1, "videoURL": myVideoUrl};
                mcu.SplitVideoScreen(1, [user1]);
            });

            //创建本地视频流失败
            rtc.on("stream_create_error", function () {
                console.warn("创建本地视频流失败");
            });

            //接收到其他用户的视频流
            rtc.on('pc_add_stream', function (stream, socketId) {
                var peerInfo = rtc.getUserInfoBySocketId(socketId);
                    if(peerInfo != null && !IsStringEmpty(peerInfo.userId)){
                        console.log("开始将用户"+peerInfo.userName+"加入到视频列表中")
                        var myVideoUrl = URL.createObjectURL(stream);
                        var user = {"userId": peerInfo.userId, "userName":peerInfo.userName, "videoURL": myVideoUrl};
                        mcu.addUserVideo(user);

                    if(Object.keys(rtc.peerConnections).length === 1){
                        //alert("调用  bound.jSVideoNum");
                        console.log("开始调用bound.JSVideoNum...")
                        try {
                            bound.jSVideoNum("'2'", '');
                        }catch(error){
                            console.log("在调用bound.jsVideoNum时出错 + " + error);
                        }
                    }
                }else{
                    console.warn("pc_add_stream, 增加新用户失败，因参数不全", peerInfo);
                }
            });

            //删除其他用户
            rtc.on('remove_peer', function (userId) {
                if(!IsStringEmpty(userId)){
                    console.log("开始从视频列表中删除用户"+ userId);
                    mcu.removeUserVideo(userId);
                }else{
                    console.warn("remove_peer, 删除用户失败，因参数不全", userId);
                }
            });
        }

        //连接WebSocket视频控制中心
        function connectWSServer() {
            if (!IsStringEmpty(currRoomNum)) {
                //连接WebSocket服务器
                var wsUrl = "wss:" + window.location.href.substring(window.location.protocol.length).split('#')[0];
                rtc.connect(wsUrl, currRoomNum, userID, userName);
                console.log("连接 WebSocket服务器:" + wsUrl, currRoomNum);
            } else {
                console.log("因参数中会议号为空，暂时不初始化websocket连接");
            }
        }

        //切换摄像头，参数为摄像头名称
        function switchCamera(camName){
            var camId = getCameraIdByName(camName);
            if(camId == null || camId.length==0){
                console.log("切换摄像头失败，非法的摄像头名称,{" + camName + "}");
                return;
            }

            //如果会议已停止，则不加载摄像头
            if (!rtc.isLive()) {
                console.log("当前未参加会议，不必重新加入会议");
            }else{
                var roomNum = currRoomNum;
                unjoin();

                currVideoId = camId;
                currRoomNum = roomNum;
                setTimeout("join(" + roomNum +")", parseInt(1200 * Math.random()));
            }
        }

        //获取视频数量
        function getVideosNumber() {
            var videoNumber = document.getElementsByTagName("video").length;
            return videoNumber;
        }

        //加入会议室
        function join(roomid) {
            if (roomid == null || roomid.length == 0) {
                console.log("roomid为空，加入会议失败");
                return;
            }

            if (rtc.isLive()) {
                console.log("会议已经开始，不需要再次join");
                return;
            }

            //如果没有摄像头，需要再次指定（在不刷新页面的情况下，多次join会出现摄像头错乱，所以重新指定比较好）
            if(currVideoId == null){
                currVideoId = getFreeCamId();
            }

            currRoomNum = roomid;
            setTimeout("connectWSServer()", parseInt(1200 * Math.random()));
        }

        //退出会议室，并断开WebSocket连接
        function unjoin() {
            currVideoId = null;
            currRoomNum = null;
            if(rtc.isLive()){
                rtc.unConnect();
            }else{
                console.log("rtc连接已处于关闭状态，不需要再次关闭");
            }
        }

        //按数字分屏
        function divScreen(num) {
            num = parseInt(num);
            mcu.SplitVideoScreen(num);
        }

    </script>
</head>
<body onload="init();">
<div id="screenContainer"/>
</body>
</html>
